﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WFDAL
{
    public class NewConverter
    {
        /// <summary>
        /// 功能說明：轉換DataRow數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public static string WriteDataRow(DataRow row)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (DataColumn column in row.Table.Columns)
            {
                sb.AppendFormat("\"{0}\":", column.ColumnName);
                sb.Append(WriteValue(row[column]));
                sb.Append(",");
            }
            // Remove the trailing comma.
            if (row.Table.Columns.Count > 0)
            {
                --sb.Length;
            }
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換DataSet數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string WriteDataSet(DataSet ds)
        {
            return WriteDataTable(ds.Tables[0]);

            StringBuilder sb = new StringBuilder();
            sb.Append("{\"Tables\":{");
            foreach (DataTable table in ds.Tables)
            {
                sb.AppendFormat("\"{0}\":", table.TableName);
                sb.Append(WriteDataTable(table));
                sb.Append(",");
            }
            // Remove the trailing comma.
            if (ds.Tables.Count > 0)
            {
                --sb.Length;
            }
            sb.Append("}}");
            return sb.ToString();
        }

        /// <summary>
        /// 功能說明：轉換DataTable數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static string WriteDataTable(DataTable table)
        {
            if (table == null)
                return "{\"Rows\":[]}";
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"Rows\":[");
            foreach (DataRow row in table.Rows)
            {
                sb.Append(WriteDataRow(row));
                sb.Append(",");
            }
            // Remove the trailing comma.
            if (table.Rows.Count > 0)
            {
                --sb.Length;
            }
            sb.Append("]}");
            return sb.ToString();
        }


        public static string JsonForJqgrid(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append("\"page\":1,\"total\":1,\"records\":" + dt.Rows.Count + ",\"rows\"");
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        public static string DataTableToJson(DataTable table)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"page\":1,\"total\":" + table.Rows.Count + ",\"records\":" + table.Rows.Count + ",\"rows\"");
            sb.Append(":[");
            foreach (DataRow row in table.Rows)
            {
                sb.Append(WriteDataRow(row));
                sb.Append(",");
            }
            // Remove the trailing comma.
            if (table.Rows.Count > 0)
            {
                --sb.Length;
            }
            sb.Append("]}");
            return sb.ToString();
        }

        /// <summary>
        /// 功能說明：轉換Enum數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string WriteEnumerable(IEnumerable e)
        {
            StringBuilder sb = new StringBuilder();
            bool hasItems = false;
            sb.Append("[");
            foreach (object val in e)
            {
                sb.Append(WriteValue(val));
                sb.Append(",");
                hasItems = true;
            }
            // Remove the trailing comma.
            if (hasItems)
            {
                --sb.Length;
            }
            sb.Append("]");
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換Hashtable數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string WriteHashtable(Hashtable e)
        {
            StringBuilder sb = new StringBuilder();
            bool hasItems = false;
            sb.Append("{");
            foreach (string key in e.Keys)
            {
                sb.AppendFormat("\"{0}\":", key.ToLower());
                sb.Append(WriteValue(e[key]));
                sb.Append(",");
                hasItems = true;
            }
            // Remove the trailing comma.
            if (hasItems)
            {
                --sb.Length;
            }
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換Object數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string WriteObject(object o)
        {
            StringBuilder sb = new StringBuilder();
            MemberInfo[] members = o.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public);
            sb.Append("{");
            bool hasMembers = false;
            foreach (MemberInfo member in members)
            {
                bool hasValue = false;
                object val = null;
                if ((member.MemberType & MemberTypes.Field) == MemberTypes.Field)
                {
                    FieldInfo field = (FieldInfo)member;
                    val = field.GetValue(o);
                    hasValue = true;
                }
                else if ((member.MemberType & MemberTypes.Property) == MemberTypes.Property)
                {
                    PropertyInfo property = (PropertyInfo)member;
                    if (property.CanRead && property.GetIndexParameters().Length == 0)
                    {
                        val = property.GetValue(o, null);
                        hasValue = true;
                    }
                }
                if (hasValue)
                {
                    sb.Append("\"");
                    sb.Append(member.Name);
                    sb.Append("\":");
                    sb.Append(WriteValue(val));
                    sb.Append(",");
                    hasMembers = true;
                }
            }
            if (hasMembers)
            {
                --sb.Length;
            }
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換String數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string WriteString(string s)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\"");
                        break;
                    case '\\':
                        sb.Append("\\\\");
                        break;
                    case '\b':
                        sb.Append("\\b");
                        break;
                    case '\f':
                        sb.Append("\\f");
                        break;
                    case '\n':
                        sb.Append("\\n");
                        break;
                    case '\r':
                        sb.Append("\\r");
                        break;
                    case '\t':
                        sb.Append("\\t");
                        break;
                    //case '<':
                    //    sb.Append("&lt;");
                    //    break;
                    //case '>':
                    //    sb.Append("&gt;");
                    //    break;
                    //case '&':
                    //    sb.Append("&amp;");
                    //    break;
                    default:
                        //int i = (int)c;
                        //if (i < 32 || i > 127)
                        //{
                        //    sb.AppendFormat("\\u{0:X04}", i);
                        //}
                        //else
                        //{
                        sb.Append(c);
                        //}
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換Value數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string WriteValue(object val)
        {
            StringBuilder sb = new StringBuilder();
            if (val == null || val == System.DBNull.Value)
            {
                sb.Append("\"\"");
            }
            else if (val is string || val is Guid)
            {
                sb.Append(WriteString(val.ToString()));
            }
            else if (val is bool)
            {
                sb.Append(val.ToString().ToLower());
            }
            else if (val is double ||
                val is float ||
                val is long ||
                val is int ||
                val is short ||
                val is byte ||
                val is decimal)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture.NumberFormat, "{0}", val);
            }
            else if (val.GetType().IsEnum)
            {
                sb.Append((int)val);
            }
            else if (val is DateTime)
            {
                sb.Append("new Date(\"");
                sb.Append(((DateTime)val).ToString("MMMM, d yyyy HH:mm:ss", new CultureInfo("en-US", false).DateTimeFormat));
                sb.Append("\")");
            }
            else if (val is DataSet)
            {
                sb.Append(WriteDataSet(val as DataSet));
            }
            else if (val is DataTable)
            {
                sb.Append(WriteDataTable(val as DataTable));
            }
            else if (val is DataRow)
            {
                sb.Append(WriteDataRow(val as DataRow));
            }
            else if (val is Hashtable)
            {
                sb.Append(WriteHashtable(val as Hashtable));
            }
            else if (val is IEnumerable)
            {
                sb.Append(WriteEnumerable(val as IEnumerable));
            }
            else
            {
                sb.Append(WriteObject(val));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 功能說明：轉換object數據為JSON類型
        /// 創建人:Aaron
        /// 創建時間:2010/01/25
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// 異動人:
        /// 異動時間:
        /// 異動原因:
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string Convert2Json(object o)
        {
            StringBuilder sb = new StringBuilder();
            WriteValue(o);
            return sb.ToString();
        }

        /// <summary>
        /// Table 轉換為HTML Table String
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToHTML(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                string reportHTML = "";
                reportHTML = "<table border=0 cellpadding='0' class='reportTableStyle' cellspacing='0' width='100%'>";
                for (int i = -1; i < dt.Rows.Count; i++)
                {
                    if (i == -1)
                    {
                        reportHTML += "<thead><tr>";
                        for (int m = 0; m < dt.Columns.Count; m++)
                        {
                            reportHTML += "<td>" + dt.Columns[m].ColumnName.ToString() + "</td>";
                        }
                        reportHTML += "</tr></thead>";
                    }
                    else if (i == 0)
                        reportHTML += "<tbody><tr>";
                    else
                        reportHTML += "<tr>";
                    if (i >= 0)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            reportHTML += "<td>" + dt.Rows[i][j].ToString() + "</td>";
                        }
                    }
                    if (i == 0)
                        reportHTML += "</tr></tbody>";
                    else if (i > 0)
                        reportHTML += "</tr>";
                }
                reportHTML += "</talbe>";
                return reportHTML;
            }
            else
                return "No Data Found!";
        }

        /// <summary>
        /// 導出Excel 傳入報表文件名稱，報表HTML內容
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="html"></param>
        /// <returns></returns>
        public string ExportExcel(string filename, string html)
        {
            try
            {
                string HtmlHead = "<HTML><HEAD><meta http-equiv=\"Content-Type\" content=\"text/html; charset=big5\" /></HEAD><body>";
                string App = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"].ToString();
                StringBuilder sb = new StringBuilder();
                sb.Append(html);
                string strPath = System.Web.HttpContext.Current.Server.MapPath("/" + App + "/files/download/excel/" + filename + ".xls");
                System.IO.StreamWriter fw = new System.IO.StreamWriter(strPath, false, System.Text.Encoding.Default);
                fw.WriteLine(HtmlHead);
                fw.WriteLine(sb.ToString());
                fw.Close();
                return "/" + App + "/files/download/excel/" + filename + ".xls";
            }
            catch (Exception error)
            {
                return "-1&" + error.ToString();
            }
        }
    }
}
